<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户编号" prop="userId" width="120" />
      <el-table-column label="用户名" prop="userName" :show-overflow-tooltip="true" />
      <el-table-column label="手机号" prop="phonenumber" width="120" />
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="150"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="600px"
      append-to-body
    >
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="0">正常</el-radio>
            <el-radio value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from "vue";
import Pagination from "@/components/Pagination/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  listUser,
  addUser,
  updateUser,
  delUser,
  getUser,
  changeUserStatus,
} from "@/api/system/user";
const { proxy } = getCurrentInstance();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: undefined,
  phonenumber: undefined,
});

const userFormRef = ref(null);
// 表格数据
const userList = ref([]);
const loading = ref(false);
const total = ref(0);

// 多选框
const multiple = ref(true);
const ids = ref([]);

// 对话框
const dialog = reactive({
  visible: false,
  title: "",
});

// 表单数据
const form = reactive({
  userId: undefined,
  userName: undefined,
  phonenumber: undefined,
  status: "0",
});

// 验证规则
const rules = reactive({
  userName: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  phonenumber: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
});

// 获取用户列表
function getList() {
  loading.value = true;
  listUser(queryParams).then((response) => {
    userList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

// 重置
function resetQuery() {
  queryParams.userName = undefined;
  queryParams.phonenumber = undefined;
  handleQuery();
}

// 多选
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId);
  multiple.value = !selection.length;
}

// 修改状态
function handleStatusChange(row) {
  const text = row.status === "0" ? "启用" : "停用";
  changeUserStatus(row.userId, row.status).then(() => {
    ElMessage.success(`${text}成功`);
  });
}

// 新增
function handleAdd() {
  reset();
  dialog.visible = true;
  dialog.title = "新增用户";
}

// 修改
function handleUpdate(row) {
  reset();
  const userId = row.userId || ids.value[0];
  getUser(userId).then((response) => {
    Object.assign(form, response.data);
    dialog.visible = true;
    dialog.title = "修改用户";
  });
}

// 删除
function handleDelete(row) {
  const userIds = row.userId || ids.value;
  ElMessageBox.confirm("是否确认删除用户编号为" + userIds + "的数据项？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    delUser(userIds).then(() => {
      getList();
      ElMessage.success("删除成功");
    });
  });
}

// 提交表单
function submitForm() {
  proxy.$refs["userFormRef"].validate((valid) => {
    if (valid) {
      if (form.userId) {
        updateUser(form).then(() => {
          ElMessage.success("修改成功");
          dialog.visible = false;
          getList();
        });
      } else {
        addUser(form).then(() => {
          ElMessage.success("新增成功");
          dialog.visible = false;
          getList();
        });
      }
    }
  });
}

// 取消
function cancel() {
  dialog.visible = false;
  reset();
}

// 重置表单
function reset() {
  form.userId = undefined;
  form.userName = undefined;
  form.phonenumber = undefined;
  form.status = "0";
  //   userFormRef.value && userFormRef.value.resetFields();
  proxy.resetForm("userFormRef");
}

// 初始化
getList();
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
